package com.example.service.impl;

import com.example.service.VerificationCodeService;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

// 实现验证码
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private final Map<String, String> codeMap = new HashMap<>();
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 6;
    private final Random random = new Random(); // 声明并初始化 random 变量

    @Override
    public byte[] generateCodeImage(String username) throws Exception {
        String code = generateRandomCode();
        codeMap.put(username, code);
        return createImage(code);
    }

    @Override
    public boolean verifyCode(String username, String code) {
        String storedCode = codeMap.get(username);
        if (storedCode != null && storedCode.equals(code)) {
            codeMap.remove(username); // 验证成功后删除验证码
            return true;
        }
        return false;
    }

    private String generateRandomCode() {
        StringBuilder sb = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i < CODE_LENGTH; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    private byte[] createImage(String code) throws Exception {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();

        // 设置背景色
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置边框
        g2.setColor(Color.BLACK);
        g2.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        // 设置字体
        Font font = new Font("Arial", Font.BOLD, 24);
        g2.setFont(font);

        // 绘制验证码
        g2.setColor(Color.BLUE);
        g2.drawString(code, 20, 28);

        // 添加干扰线
        g2.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g2.drawLine(x1, y1, x2, y2);
        }

        // 将图像转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        baos.flush();
        byte[] imageBytes = baos.toByteArray();
        baos.close();

        return imageBytes;
    }
}
